// const path=require("path");
import path from "path";
import { fileURLToPath } from "url";
// const { defineConfig, build } = require("vite");
import { defineConfig, build } from "vite";
// const vue = require("@vitejs/plugin-vue");
import vue from "@vitejs/plugin-vue";
// const vueJsx = require("@vitejs/plugin-vue-jsx");
import vueJsx from "@vitejs/plugin-vue-jsx";
import fsExtra from "fs-extra";
import fs from "fs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
//打包入口文件夹
const entryDir = path.resolve(__dirname, "../packages");
//出口文件夹
const outDir = path.resolve(__dirname, "../lib");
//基础配置
const baseConfig = defineConfig({
  configFile: false, // 禁用默认配置文件，因为我们已经有了自己的配置文件
  publicDir: false,
  plugins: [vue(), vueJsx()],
});

//rollup配置

const rollupOptions = {
  external: ["vue", "vue-router"],
  outPut: {
    globals: {
      vue: "Vue",
    },
  },
};
//全量构建的打包方法
const buildAll = async () => {
  await build({
    ...baseConfig,
    build: {
      rollupOptions,
      lib: {
        entry: path.resolve(entryDir, "index.ts"),
        name: "m-element-ui",
        fileName: "m-element-ui",
        formats: ["es", "umd"],
      },
      outDir,
    },
  });
};
//单组件打包构建
/**
 *
 * @param {组件名称} name
 */
const buildComponent = async (name) => {
  await build({
    ...baseConfig,
    build: {
      rollupOptions,
      lib: {
        entry: path.resolve(entryDir, `${name}`),
        name: `index`,
        fileName: `index`,
        formats: ["es", "umd"],
      },
      outDir: path.resolve(outDir, name),
    },
  });
};
//给每个组件生产package.json
const createPackageJson = (name) => {
  const fileStr = `
  {
    "name": "${name}",
    "main": "index.umd.js",
    "module": "index.es.js",
    "style": "styles.css"
  }
  `;
  fsExtra.outputFile(
    path.resolve(outDir, `${name}/package.json`),
    fileStr,
    "utf-8"
  );
};

//打包出库
const buildLib = async () => {
  await buildAll();

  //获取组件名称组成的数组
  const componentDirs = fs.readdirSync(entryDir).filter((item) => {
    const componentDir = path.resolve(entryDir, item);
    console.log(componentDir, "componentDir",item,entryDir);
    const isDir = fs.lstatSync(componentDir).isDirectory();
    return isDir && fs.readdirSync(componentDir).includes("index.ts");
  });
  //循环构建
  for (const name of componentDirs) {
    await buildComponent(name);
    createPackageJson(name);
  }
};
buildLib();
